package com.tanhua.server.interceptor;

import com.tanhua.server.pojo.User;
import com.tanhua.server.service.UserService;
import com.tanhua.server.utils.NoAuthorization;
import com.tanhua.server.utils.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断 被请求的方法上是否有 NoAuthorization 注解
        if (handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod) handler;
            if (null != method.getMethod().getAnnotation(NoAuthorization.class)){
                //有NoAuthorization 注解 无需验证token
                return true;
            }
        }
        //验证token
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)){
            User user = userService.queryUserByToken(token);
            if (null != user){
                //将user保存到 UserThreadLocal
                UserThreadLocal.set(user);
                return true;
            }
        }
        //如果请求头中不包含 token信息
        response.setStatus(401);
        return false;
    }
}
